import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:live_bg_mobile/common/const/app_color_const.dart';
import 'package:live_bg_mobile/widget/ripple_container.dart';

import '../common/api/public_api.dart';
import '../common/const/app_style_const.dart';
import '../common/type/address_picker_type.dart';
import '../common/util/common_util.dart';

class AddressPicker extends StatefulWidget {
  final List? dataList;
  final EdgeInsets contentPadding;
  final double headerHeight;
  final double bodyHeight;
  final void Function(AddressPickerType result) onResult;
  final bool Function(AddressPickerType result) onChecked;
  final void Function()? onCancel;

  const AddressPicker({
    key,
    required this.onResult,
    required this.onChecked,
    this.onCancel,
    this.bodyHeight = 200.0,
    this.headerHeight = 50.0,
    this.contentPadding =
        const EdgeInsets.only(left: 6.0, right: 6.0, top: 10.0, bottom: 10.0),
    this.dataList,
  }) : super(key: key);

  @override
  AddressPickerState createState() => AddressPickerState();
}

class AddressPickerState extends State<AddressPicker> {
  List provinceList = [];
  List cityList = [];
  List areaList = [];
  int? provinceIndex = -1;
  int? cityIndex = -1;
  int? areaIndex = -1;

  bool provinceListLoading = false;
  bool cityListLoading = false;
  bool areaListLoading = false;

  getResultData() {
    AddressPickerType result = AddressPickerType();

    var prs = provinceList;
    var cts = cityList;
    var ars = areaList;
    if (provinceIndex != -1 && prs.isNotEmpty) {
      result.provinceId = prs[provinceIndex!]['id'].toString();
      result.province = prs[provinceIndex!]['name'].toString();
    } else {
      result.provinceId = '';
      result.province = '';
    }

    if (cityIndex != -1 && cts.isNotEmpty) {
      result.cityId = cts[cityIndex!]['id'].toString();
      result.city = cts[cityIndex!]['name'].toString();
    } else {
      result.cityId = '';
      result.city = '';
    }

    if (areaIndex != -1 && ars.isNotEmpty) {
      result.areaId = ars[areaIndex!]['id'].toString();
      result.area = ars[areaIndex!]['name'].toString();
    } else {
      result.areaId = '';
      result.area = '';
    }

    return result;
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    if (widget.dataList == null) {
      loadProvinceList();
    } else {
      setState(() {
        provinceListLoading = true;
      });
      provinceList = widget.dataList!;
      assert(provinceList.isNotEmpty);
      setState(() {
        provinceListLoading = false;
      });
    }
  }

  loadData(pid, cb) {
    PublicApi.getChinaAddressById({"pid": pid, "useSpinning": false})
        .then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        cb(res.data["data"]);
      } else {
        cb([]);
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  loadProvinceList() {
    setState(() {
      cityList = [];
      areaList = [];
      cityIndex = -1;
      areaIndex = -1;
      provinceListLoading = true;
    });

    loadData(86, (data) {
      if (null != data && data.length > 0) {
        provinceList = data;
        provinceListLoading = false;
        setState(() {});
      } else {
        provinceList = [];
        provinceListLoading = false;
        setState(() {});
      }
    });
  }

  loadCityList() {
    dynamic params = provinceList[provinceIndex!];
    setState(() {
      cityListLoading = true;
      areaList = [];
      cityIndex = -1;
      areaIndex = -1;
    });
    loadData(params["id"], (data) {
      if (null != data && data.length > 0) {
        cityList = data;
        cityListLoading = false;
        setState(() {});
      } else {
        cityList = [];
        cityListLoading = false;
        setState(() {});
      }
    });
  }

  loadAreaList() {
    dynamic params = cityList[cityIndex!];
    setState(() {
      areaListLoading = true;
    });
    loadData(params["id"], (data) {
      if (null != data && data.length > 0) {
        areaList = data;
        areaIndex = -1;
        areaListLoading = false;
        setState(() {});
      } else {
        areaList = [];
        areaIndex = -1;
        areaListLoading = false;
        setState(() {});
      }
    });
  }

  Widget listViewItem(
      String label, TextStyle labelStyle, GestureTapCallback onTop) {
    return RippleContainer(
      onTap: onTop,
      child: Container(
        alignment: Alignment.centerLeft,
        padding: widget.contentPadding,
        child: Text(label, style: labelStyle),
      ),
    );
  }

  Widget provinceListWidget() {
    if (provinceListLoading) {
      return Container(
        decoration: const BoxDecoration(
          color: whiteColor,
        ),
        child: const Center(
          child: CupertinoActivityIndicator(
            animating: true,
          ),
        ),
      );
    }

    return Container(
        decoration: const BoxDecoration(
          color: whiteColor,
        ),
        child: ListView.builder(
            itemCount: provinceList.length,
            itemBuilder: (BuildContext context, int index) {
              return listViewItem(
                  (provinceList.isNotEmpty ? provinceList[index]['name'] : ''),
                  (provinceIndex == index ? itemActiveStyle : itemStyle), () {
                provinceIndex = index;
                loadCityList();
                setState(() {});
              });
            }));
  }

  Widget cityListWidget() {
    if (cityListLoading) {
      return Container(
        decoration: const BoxDecoration(
          color: whiteColor,
          border: Border(right: borderStyle, left: borderStyle),
        ),
        child: const Center(
          child: CupertinoActivityIndicator(
            animating: true,
          ),
        ),
      );
    }

    return Container(
      child: cityList.isEmpty
          ? Container(
              decoration: const BoxDecoration(
                color: whiteColor,
                border: Border(right: borderStyle, left: borderStyle),
              ),
            )
          : Container(
              decoration: const BoxDecoration(
                color: whiteColor,
                border: Border(right: borderStyle, left: borderStyle),
              ),
              child: ListView.builder(
                  itemCount: cityList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return listViewItem(
                        (cityList.isNotEmpty ? cityList[index]['name'] : ''),
                        (cityIndex == index ? itemActiveStyle : itemStyle), () {
                      cityIndex = index;
                      loadAreaList();
                      setState(() {});
                    });
                  }),
            ),
    );
  }

  Widget areaListWidget() {
    if (areaListLoading) {
      return Container(
        decoration: const BoxDecoration(
          color: whiteColor,
        ),
        child: const Center(
          child: CupertinoActivityIndicator(
            animating: true,
          ),
        ),
      );
    }

    return SizedBox(
        width: double.infinity,
        child: areaList.isEmpty
            ? Container(
                decoration: const BoxDecoration(color: whiteColor),
              )
            : Container(
                decoration: const BoxDecoration(color: whiteColor),
                child: ListView.builder(
                    itemCount: areaList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return listViewItem(
                          (areaList.isNotEmpty ? areaList[index]['name'] : ''),
                          (areaIndex == index ? itemActiveStyle : itemStyle),
                          () {
                        areaIndex = index;
                        setState(() {});
                      });
                    }),
              ));
  }

  Widget headerWidget() {
    return Container(
      height: widget.headerHeight,
      decoration: const BoxDecoration(
        color: whiteColor,
        border: Border(bottom: borderStyle),
      ),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            TextButton(
              style: cancelBtnStyle,
              child: const Text('取消'),
              onPressed: () {
                if (null != widget.onCancel) {
                  widget.onCancel!();
                }
                Navigator.pop(context);
              },
            ),
            TextButton(
              child: const Text('确定'),
              onPressed: () {
                AddressPickerType result = getResultData();
                if (widget.onChecked(result)) {
                  widget.onResult(result);
                  Navigator.pop(context);
                }
              },
            ),
          ]),
    );
  }

  Widget bodyWidget() {
    return SizedBox(
      height: widget.bodyHeight,
      child: Row(
        children: <Widget>[
          Expanded(child: provinceListWidget()),
          Expanded(child: cityListWidget()),
          Expanded(child: areaListWidget()),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        headerWidget(),
        bodyWidget(),
      ],
    );
  }
}
